/**
 * Thread used for sending GRIP tables out.
 */

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class GRIPSendThread extends Thread {

	private Socket	sendSocket;
		private Point pos;	
		private BufferedReader in = null;// 
		private DataOutputStream out = null;//
		private PGPeer peer = null;
		
		public GRIPSendThread(Socket sendSocket, PGPeer peer, Point pos){
			this.sendSocket = sendSocket;
			this.pos = pos;
			this.peer = peer;
		
			try {
				in = new BufferedReader(new InputStreamReader(sendSocket.getInputStream()));
				out = new DataOutputStream(sendSocket.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		
		}
		
		public void run(){			
			char[] num = new char[4];
			try {
				while(true)
				{
					// Obtain the table info for this peer
					HashMap tempGRIP = peer.getGRIPTable();
					
					if (tempGRIP == null){
						System.out.println("No link lengths provided for peer: (" + pos.getX() + ", " + pos.getY() + ")");
						break;
					}
					
					// Generate the necessary table information for the neighboring peers
					Iterator it = tempGRIP.entrySet().iterator();
					
					// Iterate through each peer and update with the correct table data
					while (it.hasNext()){
						char[] data = new char[2048];
						int counter = 1;	
						Map.Entry<Point, Integer> entry = (Map.Entry<Point, Integer>) it.next();
										
						// Number of entries being sent			
						data[0] = (char) (tempGRIP.size());
									
						Iterator itTable = tempGRIP.entrySet().iterator();
						while (itTable.hasNext()){
							Map.Entry<Point, Integer> entryTable = (Map.Entry<Point, Integer>) itTable.next();
						
							// Update the data array with the GRIP payload
							data[counter++] = (char) entryTable.getKey().getX();
							data[counter++] = (char) entryTable.getKey().getY();
							data[counter++] = (char) entryTable.getValue().intValue();							
						}
					
						GPDatagram packet = new GPDatagram(entry.getKey().getX(), entry.getKey().getY(), peer.calGRIPInPort(entry.getKey()), data.clone(), 1); 
						PSPUtil.print("Peer " + pos + " sending link length table to " + entry.getKey(), peer.getPrint());
						peer.sendPacketTable(packet);										
					
						Thread.sleep(100);
					}
					break;
				}
				
				PSPUtil.print("GRIP Send Update of " + pos + " completed\n", peer.getPrint());
							
			} catch (Exception e) {
				e.printStackTrace();			
			}		
		}
	}